import React, { useState, useEffect } from 'react';
import styles from './styles.module.css';

// 会员套餐类型
interface MembershipPlan {
  id: string;
  name: string;
  duration: number; // 月数
  price: number;
  originalPrice?: number;
  features: string[];
  popular?: boolean;
}

// 用户会员信息
interface UserMembership {
  isVip: boolean;
  vipType?: string;
  expireTime?: string;
  remainingDays?: number;
}

const MembershipPage: React.FC = () => {
  const [userMembership, setUserMembership] = useState<UserMembership>({
    isVip: false
  });
  const [selectedPlan, setSelectedPlan] = useState<string>('');
  const [isLoading, setIsLoading] = useState(false);

  // 会员套餐配置
  const membershipPlans: MembershipPlan[] = [
    {
      id: 'monthly',
      name: '月度会员',
      duration: 1,
      price: 30,
      features: [
        '无限制访问所有学习内容',
        '专属学习计划定制',
        '优先客服支持',
        '学习进度数据分析'
      ]
    },
    {
      id: 'quarterly',
      name: '季度会员',
      duration: 3,
      price: 80,
      originalPrice: 90,
      popular: true,
      features: [
        '无限制访问所有学习内容',
        '专属学习计划定制',
        '优先客服支持',
        '学习进度数据分析',
        '专属学习资料下载',
        '每月一对一指导'
      ]
    },
    {
      id: 'yearly',
      name: '年度会员',
      duration: 12,
      price: 280,
      originalPrice: 360,
      features: [
        '无限制访问所有学习内容',
        '专属学习计划定制',
        '优先客服支持',
        '学习进度数据分析',
        '专属学习资料下载',
        '每月一对一指导',
        '线下活动优先参与',
        '专属会员徽章'
      ]
    }
  ];

  // 获取用户会员信息
  const fetchUserMembership = async () => {
    try {
      const response = await fetch('http://localhost:8121/api/user/membership/info', {
        method: 'GET',
        credentials: 'include',
      });

      const data = await response.json();

      if (response.ok && data.code === 0) {
        setUserMembership(data.data);
      } else {
        console.error('获取会员信息失败:', data.message);
        // 如果获取失败，设置默认值
        setUserMembership({
          isVip: false,
          vipType: 'normal',
          expireTime: null,
          remainingDays: 0
        });
      }
    } catch (error) {
      console.error('获取会员信息失败:', error);
      // 如果请求失败，设置默认值
      setUserMembership({
        isVip: false,
        vipType: 'normal',
        expireTime: null,
        remainingDays: 0
      });
    }
  };

  // 购买会员
  const handlePurchase = async (planId: string) => {
    if (!planId) {
      alert('请选择会员套餐');
      return;
    }

    const plan = membershipPlans.find(p => p.id === planId);
    if (!plan) return;

    const confirmed = confirm(`确认购买${plan.name}会员套餐？\n价格：¥${plan.price}\n时长：${plan.duration}个月`);
    if (!confirmed) return;

    setIsLoading(true);

    try {
      const response = await fetch('http://localhost:8121/api/membership/purchase', {
        method: 'POST',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          planId: planId,
          planName: plan.name,
          duration: plan.duration,
          price: plan.price
        }),
      });

      const data = await response.json();

      if (response.ok && data.code === 0) {
        alert('购买成功！会员权益已生效');
        // 重新获取用户会员信息
        await fetchUserMembership();
      } else {
        alert(`购买失败：${data.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('购买失败:', error);
      alert('网络错误，购买失败，请稍后重试');
    } finally {
      setIsLoading(false);
    }
  };

  // 格式化剩余天数
  const formatRemainingDays = (days: number) => {
    if (days > 30) {
      const months = Math.floor(days / 30);
      const remainingDays = days % 30;
      return `${months}个月${remainingDays > 0 ? remainingDays + '天' : ''}`;
    }
    return `${days}天`;
  };

  useEffect(() => {
    fetchUserMembership();
  }, []);

  return (
    <div className={styles.membershipPage}>
      {/* 页面头部 */}
      <div className={styles.header}>
        <h1 className={styles.title}>会员中心</h1>
        <p className={styles.subtitle}>升级会员，解锁更多学习特权</p>
      </div>

      {/* 当前会员状态 */}
      <div className={styles.currentStatus}>
        <div className={styles.statusCard}>
          <div className={styles.statusInfo}>
            <h3>当前状态</h3>
            {userMembership.isVip ? (
              <div className={styles.vipStatus}>
                <span className={styles.vipBadge}>VIP会员</span>
                <p className={styles.expireInfo}>
                  剩余时间: {userMembership.remainingDays ? formatRemainingDays(userMembership.remainingDays) : '未知'}
                </p>
                <p className={styles.expireDate}>
                  到期时间: {userMembership.expireTime || '未知'}
                </p>
              </div>
            ) : (
              <div className={styles.normalStatus}>
                <span className={styles.normalBadge}>普通用户</span>
                <p className={styles.upgradeHint}>升级会员享受更多特权</p>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* 会员套餐 */}
      <div className={styles.plansSection}>
        <h2 className={styles.sectionTitle}>选择会员套餐</h2>
        <div className={styles.plansGrid}>
          {membershipPlans.map((plan) => (
            <div
              key={plan.id}
              className={`${styles.planCard} ${selectedPlan === plan.id ? styles.selected : ''} ${plan.popular ? styles.popular : ''}`}
              onClick={() => setSelectedPlan(plan.id)}
            >
              {plan.popular && <div className={styles.popularBadge}>推荐</div>}
              
              <div className={styles.planHeader}>
                <h3 className={styles.planName}>{plan.name}</h3>
                <div className={styles.planPrice}>
                  <span className={styles.price}>￥{plan.price}</span>
                  {plan.originalPrice && (
                    <span className={styles.originalPrice}>￥{plan.originalPrice}</span>
                  )}
                </div>
                <p className={styles.planDuration}>{plan.duration}个月</p>
              </div>

              <div className={styles.planFeatures}>
                <h4>会员特权</h4>
                <ul>
                  {plan.features.map((feature, index) => (
                    <li key={index}>
                      <span className={styles.checkIcon}>✓</span>
                      {feature}
                    </li>
                  ))}
                </ul>
              </div>

              <button
                className={`${styles.selectButton} ${selectedPlan === plan.id ? styles.selectedButton : ''}`}
                onClick={(e) => {
                  e.stopPropagation();
                  setSelectedPlan(plan.id);
                }}
              >
                {selectedPlan === plan.id ? '已选择' : '选择套餐'}
              </button>
            </div>
          ))}
        </div>
      </div>

      {/* 购买按钮 */}
      <div className={styles.purchaseSection}>
        <button
          className={styles.purchaseButton}
          onClick={() => handlePurchase(selectedPlan)}
          disabled={!selectedPlan || isLoading}
        >
          {isLoading ? '处理中...' : '立即购买'}
        </button>
        <p className={styles.purchaseNote}>
          * 购买后立即生效，支持7天无理由退款
        </p>
      </div>
    </div>
  );
};

export default MembershipPage;